<?php
// REGISTER PROCESS (INPUT VERIFICATIONS+DATABASE INSERT)


	//Preparing the input checkings
	// Let's check if the email already exist in database. It musn't cause it is the data the user will use to log in.
					$req = $db->prepare('SELECT id FROM jktrade_users WHERE email = :email');
					$req->execute(array('email' => $_POST['email']));
					$result = $req->fetch();
	// Calculating the age
					if(isset($_POST['birth']) AND $_POST['birth']!=NULL)
						{//This age checking function isn't mine (I hate manipulating time in php). Courtesy of http://stackoverflow.com/questions/3776682/php-calculate-age
											$dob = strtotime(str_replace("/","-",$_POST['birth']));       
											$tdate = time();
											$age = 0;
											while( $tdate > $dob = strtotime('+1 year', $dob))
											{
												++$age;
											}
						}
	// Checking the captcha
	$hash_captcha=sha1($_POST['captcha']);
// INPUT CHECK / for security
if($_POST['email']==NULL OR $_POST['password']==NULL OR $_POST['gender']==NULL OR $_POST['firstname']==NULL OR $_POST['surname']==NULL OR $_POST['phone']==NULL OR $_POST['address']==NULL OR $_POST['birth']==NULL OR $age<18 OR $_POST['terms']=NULL OR $result==true OR !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) OR $hash_captcha!=$_POST['cc'])
{ // something went wrong completing the form
echo'
<section id="home" class="home boxed">
		<div class="container">		
			<!-- Text -->
			<div class="sixteen columns">
			';
			if($_POST['firstname']!=NULL) // Let's custom the error message a little bit
			{	echo'<h2 class="title">Sorry, '.$_POST['firstname'].'.</h2>'; }
			else
			{ 	echo'<h2 class="title">Sorry, sir.</h2>'; }
			
			echo'
				<div class="subtitle">
					<p class="small">
						It seems you have missed some fields in the registration form. Here are the things you forgot to fill.
					</p>
					<div class="register">
					<form novalidate="novalidate" method="post" action="../account/" id="register-form" class="register-form"/>
					<h4>Missing information </h4>
					';
					if($_POST['email']==NULL){echo'<input name="email" id="email" placeholder="Enter your email..." type="email"/>';} 
					else 
					{ 
						if ($result) // CRITICAL ERROR !!  EMAIL already registred
						{
						echo'<legend style="color: red;">Oops.. It seems like that your e-mail '.$_POST['email'].' is already used !</legend> <input name="email" id="email" placeholder="Change the email..." type="email"/>';
						}
						else //The email isn't used, but did the user typed a real email ? let's check if it looks like one
						{	
							if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
							{
								echo '<legend style="color: red;">Oops.. '.$_POST['email'].' doesn\'t seem to be an e-mail, actually... </legend> <input name="email" id="email" placeholder="Change the email..." type="email"/>';
							}
							else
							{
								echo'<input type="hidden" name="email" value="'.$_POST['email'].'" />';
							}
						}
					}
					
					if($_POST['password']==NULL){echo'<input name="password" id="password" placeholder="Enter your desired password..." type="password"/>';} else {echo'<input type="hidden" name="password" value="'.$_POST['password'].'" />';}
					if($_POST['gender']==NULL){echo'<select name="gender" id="gender" placeholder="Gender"><option value="male">Mr.</option><option value="female">Mrs.</option></select>';} else {echo'<input type="hidden" name="gender" value="'.$_POST['gender'].'" />';}
					if($_POST['firstname']==NULL){echo'<input name="firstname" id="firstname" placeholder="First name" type="text"/>';} else {echo'<input type="hidden" name="firstname" value="'.$_POST['firstname'].'" />';}
					if($_POST['surname']==NULL){echo'<input name="surname" id="surname" placeholder="Surname" type="text"/>';} else {echo'<input type="hidden" name="surname" value="'.$_POST['surname'].'" />';}
					if($_POST['phone']==NULL){echo'<input name="phone" id="phone" placeholder="Phone number..." type="text"/>';} else {echo'<input type="hidden" name="phone" value="'.$_POST['phone'].'" />';}
					if($_POST['birth']==NULL){echo'<input name="birth" id="birth" placeholder="Date of birth (YYYY-MM-DD)..." type="text"/>';} 
					if($_POST['address']==NULL){echo'<textarea name="address" id="address" placeholder="Address"></textarea>';} else {echo'<input type="hidden" name="address" value="'.$_POST['address'].'" />';}
					if($_POST['birth']!=NULL)
					{
					if($age<18)
					{
					echo '<h4>Unvalid information </h4><legend style="color: red;">You must be aged at least 18 to use Jönkötrade<input name="birth" id="birth" placeholder="Date of birth (YYYY-MM-DD)..." type="text"/></legend>';
					}
					else{echo'<input type="hidden" name="birth" value="'.$_POST['birth'].'" />';}
					}
					if($hash_captcha!=$_POST['cc'])
					{
					//First, let's generate a random string
					$randomStringR = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 7); 
					//Then, let's hash it
					$hash_stringR = sha1($randomStringR);		
					echo'
					<p style="color: red;"><label>Seems you typed a wrong captcha. Are you a human ? Try again !</label></p>
					<legend><canvas id="captchaR" width="250" height="50"></canvas>
					<script>
					var ctxR = document.getElementById(\'captchaR\').getContext(\'2d\');
					var kittyR = new Image();
					kittyR.src = \'../data/img/captchagrid.png\';
					kittyR.onload = function(){
					  ctxR.drawImage(this, 0,0,this.width, this.height);
					  ctxR.font         = \'45px Tequillasunrise\';
					  ctxR.fillStyle = \'#333399\';
					  ctxR.textBaseline = \'top\';
					  ctxR.fillText  (\''.$randomStringR.'\', 10, 2);
					};
					</script>
					<input name="captcha" id="captchafield" placeholder="Retype captcha..." type="text"/></legend>
					<input type="hidden" name="cc" value="'.$hash_stringR.'" />';
					}
					else
					{
					echo'<input type="hidden" name="captcha" value="'.$_POST['captcha'].'" />
					<input type="hidden" name="cc" value="'.$_POST['cc'].'" />
					';
					}
					if(isset($_POST['terms']) AND $_POST['terms']=="checked"){echo'<input type="hidden" name="terms" value="checked" />';} else {echo'<p style="color: red;"><label><input type="checkbox" name="terms" value="checked" /> You must accept <a>the terms of condition</a>.</label></p>';}
					
					echo'
					<input type="hidden" name="active" value="notyet" />
					<input type="hidden" name="op" value="register" />
					<input value="Register!" class="button" type="submit">
				</form>
				</div>
				</div> <!-- /.subtitle -->
				</div><!-- /.sixteen columns -->

					

		</div> <!-- /.container -->
	</section> <!-- #home -->
';
}
else // EVERYTHING IS CORRECT !! LET'S DO THIS ! SAVING USER IN THE DATABASE
{
//Generating full name & registration date
$gen_name = $_POST['firstname'] . " " . $_POST['surname'];
$actualdate = date("Y-m-d H:i:s");

// Connecting to the database //
try
{
	$db;
}
catch(Exception $e) //if there's some trouble
{
        die('Error connecting to the database : '.$e->getMessage());
}

// SECURITY !!  HASHING THE PASSWORD before saving it in the database
$hash_pwd = sha1($_POST['password']);


// Insertion
$req = $db->prepare('INSERT INTO jktrade_users(email, pwd, gender, name, firstname, surname, phone, birth, address, active, regdate, last_ip, acctype) 
										VALUES(:email, :password, :gender, :name, :firstname, :surname, :phone, :birth, :address, :active, :regdate, :last_ip, :acctype)');
$req->execute(array(
    'email' => $_POST['email'],
    'password' => $hash_pwd,
	'gender' => $_POST['gender'],
    'name' => $gen_name,
	'firstname' => $_POST['firstname'],
	'surname' => $_POST['surname'],
	'phone' => $_POST['phone'],
	'birth' => $_POST['birth'],
	'address' => $_POST['address'],
	'active' => $_POST['active'],
	'regdate' => $actualdate,
	'last_ip' => $_SERVER['REMOTE_ADDR'],
	'acctype' => "member"
	));

echo'
<section id="home" class="home boxed">
		<div class="container">		
			<!-- Text -->
			<div class="sixteen columns">
				<h2 class="title">Nicely done, '.$_POST['firstname'].'. Welcome to Jönkötrade !</h2>
				
				<div class="subtitle">
					<h5>
						You will receive an e-mail soon to confirm your account. If you don\'t, please check your SPAM folder. 
					</h5>

				</div> <!-- /.subtitle -->
				</div><!-- /.sixteen columns -->

					

		</div> <!-- /.container -->
	</section> <!-- #home -->
';
}//end of else 
?>